<template>
    <el-card shadow="always" style="margin: 20px;">

        <el-form class="form" :inline="true">
            <el-form-item label="用户名">
                <el-input v-model="username" style="width: 240px" placeholder="请输入用户名" />
            </el-form-item>

            <!-- 按钮也可以放在表单项里面 -->
            <el-form-item>
                <el-button type="primary" @click="search" :disabled="username?false:true">查询</el-button>
                <el-button @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="max-width: 100%;margin: 20px;">
        <div style="margin-bottom: 10px;">


            <el-button type="primary" @click="showDrawer">添加用户</el-button>
            <el-popconfirm confirm-button-text="Yes" cancel-button-text="No" icon-color="#626AEF" title="确定要批量删除吗?"
                @cancel="cancelMore" @confirm="handleMoreDelete">
                <template #reference>
                    <el-button type="danger" :disabled="selectArr.length?false:true">批量删除</el-button>
                </template>
            </el-popconfirm>
        </div>
        <el-table :data="userArr" border style="width: 100%" @selection-change="handleSelectChange" ref="tableRef">
            <el-table-column type="selection" width="40 " />
            <el-table-column type='index' label="#" width="40" />
            <el-table-column prop="id" label="id" width="40" />
            <!-- <el-table-column prop="logoUrl" label="图片" width="180" /> -->

            <el-table-column prop="username" label="用户名字" width="120" />
            <el-table-column prop="name" label="用户名称" width="110" />
            <el-table-column prop="roleName" label="用户角色" width="160" />
            <el-table-column prop="createTime" label="创建时间" width="160" />
            <el-table-column prop="updateTime" label="更新时间" width="180" />
            <el-table-column label="操作" min-width="120">
                <template #="scope">
                    <el-button size="small" type="primary" :icon="Edit" @click="showRole(scope.row)">分配角色
                        <!-- @click="handleClick" -->
                    </el-button>
                    <el-button size="small" type="primary" :icon="Edit" @click="updateUser(scope.row)">编辑
                        <!-- @click="handleClick" -->
                    </el-button>
                    <el-popconfirm confirm-button-text="Yes" cancel-button-text="No" icon-color="#626AEF"
                        title="Are you sure to delete this?" @cancel="cancelEvent"
                        @confirm="handleDelete(scope.row.id)">
                        <template #reference>
                            <el-button size="small" type="primary" :icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="pageNo" v-model:page-size="limit" :page-sizes="[4,8 , 12, 16]"
            :background="true" layout=" prev, pager, next, jumper,->,sizes,total" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        <!-- 新增修改对话框 -->

        <el-drawer v-model="drawer" :title="userParams.id?'修改用户':'添加用户'" :direction="direction">

            <template #default>
                <div>
                    <el-form :model="userParams" ref="ruleFormRef" :rules="rules">
                        <el-form-item label="用户姓名" label-width="80px" prop="username">
                            <el-input v-model="userParams.username" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="用户昵称" label-width="80px">
                            <el-input v-model="userParams.name" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="用户密码" label-width="80px" prop="password" v-if="!userParams.id">
                            <el-input v-model="userParams.password" autocomplete="off" />
                        </el-form-item>

                    </el-form>
                </div>
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="drawer=false">取消</el-button>
                    <el-button type="primary" @click="confirmClick">确认</el-button>
                </div>
            </template>

        </el-drawer>

        <el-drawer v-model="roleDrawer" title="分配角色" :direction="direction">
            <template #default>
                <el-form :model="userParams" style="width: 80%;" ref="FormRef" :rules="rules">
                    <!-- label-width属性让左边的标题对齐 -->
                    <el-form-item label="用户姓名" label-width="80px" prop="username">
                        <el-input v-model="userParams.username" autocomplete="off" disabled />
                    </el-form-item>
                    <el-form-item label="角色列表" label-width="80px">
                        <el-checkbox v-model="checkAll" @change="handleCheckAllChange"
                            :isIndeterminate="isIndeterminate">
                            全选
                        </el-checkbox>
                        <el-checkbox-group v-model="userRole" @change="handleCheckedRoleChange">
                            <el-checkbox v-for="(role,index) in allRoles" :key="index" :value="role">
                                {{ role.roleName }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="drawer=false">取消</el-button>
                    <el-button type="primary" @click="confirmRole">确认</el-button>
                </div>
            </template>

        </el-drawer>
    </el-card>
</template>
<script setup name="user" lang="ts">
    import { ref, onMounted, reactive, nextTick } from 'vue'
    import { reqUserInfo, reqAddOrUpdateUser, reqAllRole, reqSetUserRole, reqRemoveUser, reqRemoveAllUser } from '@/api/acl/user/index.ts'

    import { Edit, Delete } from '@element-plus/icons-vue'
    import { ElMessage } from 'element-plus'
    let username = ref('')
    let pageNo = ref(1)
    //每一页展示多少条数据
    let limit = ref(5)
    let total = ref(0)
    let userArr = ref([])
    let userParams = reactive({
        username: '',
        name: '',
        password: '',
        role: '',
        id: undefined
    })
    //控制抽屉的方向
    let direction = ref('rtl')
    let drawer = ref(false)
    const checkAll = ref(false)
    const isIndeterminate = ref(true)
    //这个是添加修改用户表单的实例
    let ruleFormRef = ref()
    const userRole = ref([])
    const allRoles = ref([])
    //放置批量删除的数组
    const selectArr = ref([])
    const tableRef=ref()
    onMounted(
        () => {
            reqUser();
        }
    )
    const handleCheckAllChange = (val: boolean) => {
        // val代表全选按钮状态
        userRole.value = val ? allRoles.value : []
        isIndeterminate.value = false
    }
    const handleCheckedRoleChange = (value: any) => {
        console.log(value);
        Object.assign(userRole, value)
        // value代表勾选的内容
        const checkedCount = value.length
        checkAll.value = checkedCount === allRoles.value.length
        isIndeterminate.value =
            checkedCount > 0 && checkedCount < allRoles.value.length
    }
    // value是用户输入的值
    const check = (rule: any, value: any, callback: any) => {
        if (value.length >= 5) {
            callback()
        } else {
            callback(new Error('用户名必须大于5位字符'))
        }
    }
    const checkPw = (rule: any, value: any, callback: any) => {
        if (value.length >= 6) {
            callback()
        } else {
            callback(new Error('密码必须大于6位字符'))
        }
    }
    const rules = reactive({
        username: [
            { required: true, trigger: 'blur', validator: check },

        ],
        password: [
            { required: true, trigger: 'blur', validator: checkPw }
        ]
    })
    let roleDrawer = ref(false)


    const reqUser = async () => {
        console.log(username.value);
        let res = await reqUserInfo(pageNo.value, limit.value, username.value)
        userArr.value = res.data.records
        total.value = res.data.total
    }
    const handleSizeChange = () => {
        pageNo.value = 1
        reqUser()
    }
    const handleCurrentChange = () => {
        reqUser()
    }
    //新增和修改操作
    const showDrawer = () => {
        drawer.value = true
        userParams.username = ''
        userParams.password = ''
        userParams.name = ''
        userParams.id = undefined
        nextTick(() => {
            // 在打开这个对话框时，form这个dom结构还没有出现
            ruleFormRef.value.clearValidate('username')
            ruleFormRef.value.clearValidate('password')
        })

    }
    const cancelEvent = () => {
        ElMessage({
            type: 'info',
            message: '取消删除'
        })

    }
    const confirmClick = async () => {
        await ruleFormRef.value.validate()
        let res = await reqAddOrUpdateUser(userParams)
        if (res.code === 200) {
            reqUser()
            ElMessage({
                type: "success",
                message: userParams.id ? '修改成功' : '添加成功'
            })
            drawer.value = false
        } else {
            ElMessage({
                type: "error",
                message: userParams.id ? '修改失败' : '添加失败'
            })
        }
    }

    const showRole = async (row) => {
        roleDrawer.value = true;
        Object.assign(userParams, row)
        console.log(row);
        let res = await reqAllRole(row.id)
        allRoles.value = res.data.allRolesList
        userRole.value = res.data.assignRoles
        console.log(userRole.value);
    }
    const updateUser = (row) => {
        drawer.value = true;
        Object.assign(userParams, row)
    }
    const confirmRole = async () => {
        let roleIdList=userRole.value.map(item=>item.id)
        let res = await reqSetUserRole({ userId: userParams.id, roleIdList: roleIdList })
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '分配角色成功'
            })
            reqUser()
            roleDrawer.value=false
        } else {
            ElMessage({
                type: 'error',
                message: '分配角色失败'
            })
        }
    }
    const handleDelete = async (id) => {
        let res = await reqRemoveUser(id)
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '删除成功'
            })
            reqUser(userArr.value.length>1?pageNo.value:pageNo.value-1)
        } else {
            ElMessage({
                type: 'error',
                message: '删除失败'
            })
        }
    }
    //处理批量删除
    const handleSelectChange = async (newSelection) => {
 
        selectArr.value = newSelection.map(item =>item.id)
        console.log(selectArr.value);

    }
    const handleMoreDelete = async () => {
        let res = await reqRemoveAllUser(selectArr.value)
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '批量删除成功'
            })
            reqUser(userArr.value.length>1?pageNo.value:pageNo.value-1)
        } else {
            ElMessage({
                type: 'error',
                message: '批量删除失败'
            })
        }
    }
    const cancelMore=()=>{
        ElMessage({
            type: 'info',
            message: '取消删除'
        })
tableRef.value.clearSelection()
    }
    const search=()=>{
        reqUser();
        username.value=''

    }
    const reset=()=>{
        reqUser();
    }
</script>
<style scoped lang='scss'>
    .form {
        display: flex;
        justify-content: space-between;
    }
</style>